// ============================== 导入依赖 ============================== //

import CORE from '@/CORE'
import Client from '@api/elemac/api/DeviceActionPlanApi'

import ComClass from '@api/ComQuery'
import ListClass from '@api/elemac/model/DeviceActionPlanReq'
import OneClass from '@api/elemac/model/DeviceActionPlanAnalysisReq'
import DelClass from '@api/elemac/model/DeviceActionPlanDeleteReq'
import BaseClass from '@api/elemac/model/DeviceActionPlanDto'

const AddClass = ListClass
const EditClass = ListClass

const CLIENT = CORE.grpcCLIENT(Client)
const COM = [ComClass, 'comQuery']
const BASE = [BaseClass, 'dto']

// ============================== 导出远程接口 ============================== //

export default {
  // —————————————————————————————— 列表 —————————————————————————————— //

  async getList(param, TIP = '查询列表') {
    const DTO = CORE.grpcDTO(ListClass, param, COM, BASE)
    const resp = await CORE.grpc(TIP, CLIENT, 'deviceActionPlanQuery', DTO)
    return [resp.comQuery.totalCount, resp.dto || []]
  },
  transList(arr) {
    arr.forEach((item) => {
      item.deviceNum = item.deviceId ? item.deviceId.split(',').length : 0
    })
    return arr
  },

  // —————————————————————————————— 单项 —————————————————————————————— //

  async getOne(one, TIP = '查询详情') {
    const DTO = CORE.grpcDTO(OneClass, { cron: one.cron, num: 10 })
    try {
      const resp = await CORE.grpc(TIP, CLIENT, 'deviceActionPlanAnalysis', DTO)
      return { ...one, times: resp.times || [] }
    } catch (e) {
      return { ...one, errMsg: e.message.replace(`${TIP}：`, '') }
    }
  },

  // —————————————————————————————— 增 —————————————————————————————— //

  async add(one, TIP = '新增') {
    const DTO = CORE.grpcDTO(AddClass, one, BASE)
    await CORE.grpc(TIP, CLIENT, 'deviceActionPlanSave', DTO)
    return CORE.grpcOK(TIP)
  },

  // —————————————————————————————— 改 —————————————————————————————— //

  async edit(one, TIP = '修改') {
    const DTO = CORE.grpcDTO(EditClass, one, BASE)
    await CORE.grpc(TIP, CLIENT, 'deviceActionPlanUpdate', DTO)
    return CORE.grpcOK(TIP)
  },

  // —————————————————————————————— 删 —————————————————————————————— //

  async del({ id }, TIP = '删除') {
    const DTO = CORE.grpcDTO(DelClass, { ids: id })
    await CORE.grpc(TIP, CLIENT, 'deviceActionPlanDelete', DTO)
    return CORE.grpcOK(TIP)
  },
}
